<?php

class UserController extends Zend_Controller_Action {

    public function init() {
        /* Initialize action controller here */
    }
    
    public function activateAction() {
      // user is admin
      $user = Zend_Auth::getInstance()->getIdentity();
      if (!$user->isAdmin()) {
          $this->_redirect("index");
      }
      
      // activate the account
      $id = $this->getRequest()->getParam("id");
      $db = new Application_Model_UserMapper();
      $account = $db->findUserById($id);
      $account->set_activated(true);
      $account->save();

    }

    public function signupAction()
    {
      $req = $this->getRequest();
      if (!$req->isPost()) {
        $this->view->form = new Application_Form_Signup(
          array('action' => '/user/signup'));
        return $this->render('signup');
      }
      
      $form = new Application_Form_Signup();
      if (!$form->isValid($req->getPost())) {
          $this->view->form = $form;
          return $this->render('signup');
      }
      
      // user name exists
      $values = $form->getValues();
      $query =  new Application_Model_UserMapper();
      if($query->findByLogin($values['login']) != null) {
        $form->setDescription('Login already choosen');
        $this->view->form = $form;
        return $this->render('signup');
      }
      // missenterred password
      if($values['verification'] != $values['password']) {
        $form->setDescription('Password and verification do not match');
        $this->view->form = $form;
      }
      
      // add user
      $user = new Application_Model_User(
        null,
        $values['login'],
        sha1($values['password']),
        $values['email'],
        false,
        'user', 
        false);
      $id = $query->save($user);
      
      // email admins
      $config = new Zend_Config_Ini(APPLICATION_PATH . "/configs/application.ini", "production");
      $transport = new Zend_Mail_Transport_Smtp($config->resources->mail->host,
              array('auth' => 'login',
                    'username' => $config->resources->mail->user,
                    'password' => $config->resources->mail->password,
                    'ssl' => 'tls',
                    'port' => 587));
      Zend_Mail::setDefaultTransport($transport);
      $mail = new Zend_Mail();
      $body = 'New user: '.$values['login']. ' just signed up.<br />';
      $url = $this->view->serverUrl() . $this->view->url(array('id'=>$id), "activate", true);
      $body .= '<a href="'.$url.'">Activate the account</a>';
      $mail->setBodyHtml($body);
      $mail->setFrom($config->resources->mail->user, 'Robot Kollekthor');
      $sa = $query->findAllSuperAdmins();
      foreach($sa as $u) {
        $mail->addTo($u->email(), $u->login());
      }
      $mail->setSubject('New user subscription');
      $mail->send();
      $this->view->result = "<h2>Your account request has been sent to the server admin.</h2>";
      $this->view->result .= "<p>You will be alerted when your account is activated.</p>";
    }

    public function indexAction() {
        $this->view->form = $this->getForm();
    }

    public function getForm() {
        $url = $this->_helper->url(null, "login", true);
        return new Application_Form_Login(array('action' => $url));
    }

    public function getAuthAdapter(array $params) {
        return new Buzz_AuthAdapter($params["login"], $params["password"]);
    }

    public function preDispatch() {
        if (Zend_Auth::getInstance()->hasIdentity()) {
            if ('logout' != $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index', 'index');
            }
        } else {
            if ('logout' == $this->getRequest()->getActionName()) {
                $this->_helper->redirector('index');
            }
        }
    }

    public function loginAction() {
        $req = $this->getRequest();

        if (!$req->isPost()) {
            return $this->_helper->redirector('index');
        }

        $form = $this->getForm();
        if (!$form->isValid($req->getPost())) {
            $this->view->form = $form;
            return $this->render('index');
        }

        $adapter = $this->getAuthAdapter($form->getValues());
        $auth = Zend_Auth::getInstance();
        $result = $auth->authenticate($adapter);
        if (!$result->isValid()) {
            // Invalid credentials
            $form->setDescription('Invalid credentials provided');
            $this->view->form = $form;
            return $this->render('index'); // re-render the login form
        }
        // We're authenticated! Redirect to the home page
        $this->_helper->redirector('index', 'index');
    }

    public function logoutAction() {
        Zend_Auth::getInstance()->clearIdentity();
        $this->_helper->redirector('index');
    }
}